import java.io.BufferedWriter;
import java.io.FileWriter;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.dom4j.io.DOMReader;
import org.w3c.dom.Document;
import org.w3c.dom.Element;

public class Main {

	public static void main(String[] args) {

		createXMLDocument();

	}

	public static void createXMLDocument() {
		try {
			DocumentBuilderFactory factory = DocumentBuilderFactory
					.newInstance();
			DocumentBuilder builder = factory.newDocumentBuilder();
			Document document = builder.newDocument();

			Element root = document.createElement("XML");

			Element person = document.createElement("Person");
			Element name = document.createElement("Name");
			Element vorname = document.createElement("Vorname");

			name.appendChild(document.createTextNode("Mustermann"));
			person.appendChild(name);

			vorname.appendChild(document.createTextNode("Karl"));
			person.appendChild(vorname);

			root.appendChild(person);
			document.appendChild(root);

			DOMReader reader = new DOMReader();
			org.dom4j.Document doc2 = reader.read(document);
			System.out.println(doc2.asXML());

			FileWriter ausgabestrom = new FileWriter("test.xml");
			BufferedWriter output = new BufferedWriter(ausgabestrom);
			output.write(doc2.asXML().toString());
			output.flush();
			output.close();

		} catch (ParserConfigurationException e) {
			e.printStackTrace();
		} catch (Throwable e) {
			e.printStackTrace();
		}
	}

}